package com.fengye.common.resolver;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @author sunlei
 * @version 1.0
 * @date 2024/6/25 14:56:45
 * @description 自定义LocalResolver解析器，用于国际化
 */
@Slf4j
@Component
public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 获取请求中的语言参数
        String language = request.getHeader("Accept-Language");
        log.info(language);
        // 获取默认的语言
        Locale locale = Locale.getDefault();

        // 如果请求的链接携带了国际化参数
        if (!StringUtils.isEmpty(language)) {
            // 格式：zh_CN、en_US
            String[] split = split = language.split("_");;
            if (split.length >= 2) {
                // 国家，地区
                locale = new Locale(split[0], split[1]);
            }
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }

    //注入Bean 自定义的国际化组件就生效了
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

}
